package cn.xu.bookstore.user.web.servlet;



import java.io.IOException;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import javax.mail.MessagingException;
import javax.mail.Session;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.itcast.commons.CommonUtils;
import cn.itcast.mail.Mail;
import cn.itcast.mail.MailUtils;
import cn.itcast.servlet.BaseServlet;
import cn.xu.bookstore.cart.domain.Cart;
import cn.xu.bookstore.user.domain.User;
import cn.xu.bookstore.user.exception.UserException;
import cn.xu.bookstore.user.service.UserService;

public class UserServlet extends BaseServlet {
	private UserService userService = new UserService();
	
	
	
	
	public String regist(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
	
		/*
		 * 1.一键封装表单数据，不全uuid激活码
		 * 2.进项表单的 基本验证(可以通过前端来做，这里就用了服务器端做了)
		 * 3.调用userServic.regist(form)，完成注册
		 * 		如果异常则保存错误信息到request并转发到msg中和实现表单数据回显
		 * 4.发送email 保存成功信息并转发到msg页面
		 */
		User form = CommonUtils.toBean(request.getParameterMap(), User.class);
		form.setUid(CommonUtils.uuid());
		form.setCode(CommonUtils.uuid()+CommonUtils.uuid());
		
		/*
		 * 表单数据的一些基本验证
		 */
		Map<String,String> errors = new HashMap<String, String>();
		String username = form.getUsername();
		if(username.trim().isEmpty() || username==null){
			errors.put("usrename", "用户名不能为空");
		}else if(username.length() <3 || username.length()>16){
			errors.put("username", "用户民的长度必须在3~10之间");
		}
		
		String password = form.getPassword();
		if(password.trim().isEmpty() || password==null){
			errors.put("password", "密码不能为空");
		}else if(password.length() <3 || password.length()>16){
			errors.put("password", "密码的长度必须在3~10之间");
		}
		
		String email = form.getEmail();
		if(email.trim().isEmpty() || email==null){
			errors.put("email", "Email不能为空");
		}else if(!email.matches("\\w+@\\w+\\.\\w+")){//xu@163.com
			errors.put("email", "Email的格式不对");
		}
		
		/*
		 * 判断errors是否有错误信息有则转发到 regist.jsp
		 */
		if(errors.size()>0){
			//数据的回显
			request.setAttribute("form", form);
			request.setAttribute("errors", errors);
			return "f:/jsps/user/regist.jsp";
		}
		
		/*
		 * 调用userService regist的方法
		 * 保存异常信息到msg中 并转发到regist.jsp 中
		 */
		try {
			userService.regist(form);
		} catch (UserException e) {
			//表单数据的回显
			request.setAttribute("form", form);
			request.setAttribute("msg", e.getMessage());
			return "f:jsps/user/regist.jsp";
		}
		
		/*
		 * 准备配置文件
		 * 发送Email并完成激活
		 */
		Properties pro = new Properties();
		pro.load(this.getClass().getClassLoader().getResourceAsStream("email_template.properties"));
		String host = pro.getProperty("host");
		String uname = pro.getProperty("uname");
		String pwd = pro.getProperty("pwd");
		String from = pro.getProperty("from");
		String to = form.getEmail();
		String subject = pro.getProperty("subject");
		String content = pro.getProperty("content");
		//给占位符的位置重新赋值 占位符{0}{1}
		content = MessageFormat.format(content, form.getCode());
		
		//获取session
		Session session = MailUtils.createSession(host, uname, pwd);
		//创建email对象 String from, String to, String subject, String content
		Mail mail = new Mail(from,to,subject,content);
		//发送email
		try {
			MailUtils.send(session, mail);
		} catch (MessagingException e) {
		}
		
		/*
		 * 保存成功信息到msg.jsp页面
		 */
		request.setAttribute("msg", "恭喜你注册成功，请马上到邮箱激活");
		return "f:/jsps/msg.jsp";
	}
	
	/*
	 * 激活
	 */
	public String active(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		/*
		 * 获取参数激活码code来激活用户
		 * 保存异常信息 转发到msg.jsp
		 */
		String code = request.getParameter("code");
		try {
			userService.active(code);
			request.setAttribute("msg", "恭喜你激活成功!请马上登录");
		} catch (UserException e) {
			request.setAttribute("msg", e.getMessage());
			return "f:/jsps/msg.jsp";
		}
		
		return "f:/jsps/msg.jsp";
	}
	
	public String login(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		/*
		 * 用户登录
		 */
		User form = CommonUtils.toBean(request.getParameterMap(), User.class);
		/*
		 * 表单的基本判断
		 */
		Map<String,String> errors = new HashMap<String, String>();
		String username = form.getUsername();
		if(username.trim().isEmpty() || username == null){
			errors.put("username", "用户名不能为空");
		}
		
		String pwd = form.getPassword();
		if(pwd.trim().isEmpty() || pwd==null){
			errors.put("password", "密码不能为空");
		}
		
		try {
			User user = userService.login(form);
			request.getSession().setAttribute("session_user", user);
			/*
			 * 用户登录成功则 给分配购物车并保存到session中
			 */
			request.getSession().setAttribute("cart", new Cart());
			
		} catch (UserException e) {
			request.setAttribute("msg", e.getMessage());
			request.setAttribute("form", form);
			return "f:/jsps/user/login.jsp";
		}
		
		return "r:/index.jsp";
	}
	
	/*
	 * 用户退出
	 */
	public String quit(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		//清空session
		request.getSession().invalidate();
		
		return "r:/jsps/user/login.jsp";
	}
	
	
	
	

}
